package cn.tedu.charging.order.dao.repository.impl;


import cn.tedu.charging.order.common.OrderStatusConstants;
import cn.tedu.charging.order.dao.mapper.OrderFailMapper;
import cn.tedu.charging.order.dao.mapper.OrderSuccessMapper;
import cn.tedu.charging.order.dao.repository.OrderRepository;
import cn.tedu.charging.order.pojo.po.ChargingOrderFailPO;
import cn.tedu.charging.order.pojo.po.ChargingOrderSuccessPO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class OrderRepositoryImpl implements OrderRepository {

    @Autowired
    private OrderSuccessMapper orderSuccessMapper;

    @Autowired
    private OrderFailMapper orderFailMapper;

    @Override
    public ChargingOrderSuccessPO getSuccessOrderByOrderNo(String orderNo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("bill_id",orderNo);
        return orderSuccessMapper.selectOne(queryWrapper);
    }

    @Override
    public ChargingOrderFailPO getFailOrderByOrderNo(String orderNo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("bill_id",orderNo);
        return orderFailMapper.selectOne(queryWrapper);
    }

    @Override
    public Integer insertFailOrder(ChargingOrderFailPO chargingOrderFailPO) {
        return orderFailMapper.insert(chargingOrderFailPO);
    }

    @Override
    public Integer insertSuccessOrder(ChargingOrderSuccessPO chargingOrderSuccessPO) {
        return orderSuccessMapper.insert(chargingOrderSuccessPO);
    }
    @Override
    public Integer updateOrderStatusFromChargingToAbnormalEnd(String orderNo) {
        //1> 从业务上能实现 但是操作了两次数据库 不推荐
        // select status from xxx where orderNo = orderNo
        //  if status ==  充电中 {
        //     update xxx set status = 异常结束 where bill_id = #{orderNo}
        //  }

        //2>update xxx set status = 异常结束 where bill_id = #{orderNo} and status = 充电中

        //要更新的目标值
        ChargingOrderSuccessPO chargingOrderSuccessPO = new ChargingOrderSuccessPO();
        //status = 异常结束
        chargingOrderSuccessPO.setBillStatus(OrderStatusConstants.ORDER_STATUS_ABNORMAL_END);

        // Wrapper 是设置 执行sql的 条件 包括 update 和 query 的条件
        UpdateWrapper updateWrapper = new UpdateWrapper();
        //bill_id = #{orderNo}
        updateWrapper.eq("bill_id",orderNo);
        //status = 充电中
        updateWrapper.eq("bill_status", OrderStatusConstants.ORDER_STATUS_CHARGING);

        return orderSuccessMapper.update(chargingOrderSuccessPO,updateWrapper);
    }
}
